$(function () {
    "use strict";

    // *********************************************************************
    // *** Event Bindings
    // *********************************************************************

        $('.ssbShowHide').bind('click', function (event) {
            // Store which button was clicked.
            j2w.SSB.$activeButton = $(event.currentTarget).closest('.socialSubscribeButton');

            var $thisSSBForm = j2w.SSB.$activeButton.find('form.frmSocialSubscribe');

            // Hide any other open social subscribe buttons.
            $.each($('ul.btnSocialSubscribe'), function (idx, obj) {
                if ($(this).data('ssbID') !== j2w.SSB.$activeButton.find('ul.btnSocialSubscribe').data('ssbID')) {
                    $(this).closest('form.frmSocialSubscribe').hide();
                }
            });

            // Reset any existing UI state (errors, etc.)
                $('.btnSocialSubscribe ul.sub').find('li').show().end().find('li.loading').hide();
                clearSSBErrorState();
                $('.emailGetter').hide();

            // Position the social subscribe button.
            ssbPrepareTo(j2w.SSB.presentation[j2w.SSB.$activeButton.find('ul.btnSocialSubscribe').data('ssbID')]);

            // Show or hide the button the user clicked.
            $thisSSBForm.css('display') === 'block' ? $thisSSBForm.hide() : $thisSSBForm.show();

            // Hide the social apply menu, if it is available.
            typeof closeSocialApplyOptions === 'function' ? closeSocialApplyOptions() : null;

            scrollForSSBDropDown();

            event.preventDefault();
            event.stopImmediatePropagation();
        });

        $('.btnSocialSubscribe .networkContainer, a.networkContainer').bind('mouseup', function (event) {
            var $getter = $(this).closest('ul').find('.emailGetter'),
                $email = $getter.find('input[type=text]');

            // Keep track of the selected social network option, and populate the UI with the moretext value for it.
                window.oSSSelected = j2w.SSB.Args.get('profileData')[$(this).data('idx')];

                $('.btnSocialSubscribe .socialMoreText').html(oSSSelected.moretext).show();

                if (!oSSSelected.moretext.length) {
                    $('.btnSocialSubscribe .socialMoreText').hide();
                }

            // Set the social subscribe type in use.
            $('form.frmSocialSubscribe').data('ssMethod',oSSSelected.shorttype);

            // Move the e-mail address getter into position.
            $getter.appendTo($(this).closest('li'));

            // If there's already a valid e-mail address in the field, we skip showing it and submit the form.
            if (j2w.Validation.isEmail($email.val())) {
                $getter.find('.start').trigger('mouseup');
            } else {
                $getter.show();
                focusSocialSubscribeInput();
            }

            scrollForSSBDropDown();
        });

        $('.btnSocialSubscribe a.manualSubscribe').click(function (event) {
            event.preventDefault();
        });
        $('.btnSocialSubscribe a.manualSubscribe').keyup(function (event) {
            if (event.keyCode === 13) {
                $(this).closest('.networkContainer').trigger('mouseup');
            }
        });

        $('form.frmSocialSubscribe').click(function (event) {
            event.stopPropagation();
        });

        $('.btnSocialSubscribe .emailGetter input.start').bind('mouseup', function (event) {
            $(this).closest('form').trigger('submit');

            event.stopImmediatePropagation();
        });

        $('.btnSocialSubscribe .emailGetter input.start').keyup(function (event) {
            if (event.which == 13) {
                $(this).closest('form').trigger('submit');
            } else if ($(this).val().length === 0) {
                clearSSBErrorState();
            }
        });

        $('form.frmSocialSubscribe').bind('submit', function (event) {
            var $form = $(this);
            var $email = $form.find('input[type=text]');

            if ($.cookies.test()) {
                if (j2w.Validation.isEmail($email.val())) {
                    // Hide any previous error state.
                    clearSSBErrorState();

                    switch ($form.data('ssMethod')) {
                        case 'li':
                            // We need to indicate that the user started this subscribe so that the authentication can respond appropriately.
                            j2w.SSB.li.subscribeStarted = true;

                            socialSubscribeCheckLI();
                            break;

                        case 'fb':
                            socialSubscribeCheckFB();
                            break;

                        default:
                            ssbSubscribeHandler({});
                            break;
                    }
                } else if ($email.val().length) {
                    setSSBErrorState(jsStr.tcemailnotvalid);
                    focusSocialSubscribeInput();
                    scrollForSSBDropDown();
                } else {
                    setSSBErrorState(jsStr.tcemailaddressrequired);
                    focusSocialSubscribeInput();
                    scrollForSSBDropDown();
                }
            } else {
                alert(jsStr.tccookiesmustbeenabled.unescapeHTML());
            }

            // Prevent firing of other bound events and the submission of the form itself.
            event.stopImmediatePropagation();
            event.preventDefault();
        });

        $('.btnSocialSubscribe a.helpA, .btnSocialSubscribe .socialbutton-help-icon').bind('mouseup keyup',function (e) {
            if (e.keyCode === 13 || e.keyCode === undefined) {
                var $helpText = $(this).find('img').data('ht');

                if (e.keyCode === 13) {
                    $(this).blur();
                }

                if ($helpText.length) {
                    alert($helpText);
                }
            }
        });

        // Set a value on each social subscribe button so that we can distinguish which is which.
        $(document).bind('ssb.setSSBIDs',function (e) {
            $.each($('ul.btnSocialSubscribe'), function (idx, obj) {
                $(this).data('ssbID',idx);

                // If the presentation method for this button is "pop", adjust the icon accordingly.
                if (j2w.SSB.presentation[idx] === 'pop') {
                    $(this).closest('.socialSubscribeButton').find('img.expose').addClass('rotated180');
                }
            });
        });

        // Closes the social subscribe menu when the user left-clicks outside of it. (This allows the user to right-click to paste their e-mail address, etc.)
        $(document).click(function (e) {
            if (e.which === 1) {
                closeSocialSubscribeOptions();
            }
        });
});

// *********************************************************************
// ** Social Subscribe Button Generic
// *********************************************************************

    // closeSocialSubscribeOptions()
    // Closes the SSB and cleans up.
    function closeSocialSubscribeOptions() {
        $('.btnSocialSubscribe .emailGetter,form.frmSocialSubscribe').hide();

        clearSSBErrorState();

        // Show the subscribe options and hide the "please wait" messaging.
        $('.btnSocialSubscribe ul.sub').find('li').show().end().find('li.loading').hide();
    }

    // clearSSBErrorState()
    // Clear the error state from the getter.
    function clearSSBErrorState() {
        $('.ssbGetterMsg')
            .html('')
            .hide()
            .siblings('input[name=email]')
            .removeClass('errorField');
    }

     // setSSBErrorState()
    // Renders a message near the SSB e-mail input field.
    function setSSBErrorState(message) {
        $('.ssbGetterMsg')
            .html(message.unescapeHTML())
            .show()
            .siblings('input[name=email]')
            .addClass('errorField');
    }

    // ssbSubscribeHandler()
    // Updates the UI and goes to subscribe.
    function ssbSubscribeHandler(options) {
        var redirURL = '/talentcommunity/subscribe/',
            $container = j2w.SSB.$activeButton.find('.btnSocialSubscribe ul.sub'),
            beforeHeight = $container.height(),
            beforeWidth = $container.width();

        // Provide default values, but override them with those values passed in.
        options = $.extend({
            socialSrc : ''
        }, options);

        // Show the please wait indicator and hide the other options before proceeding.
        $container.find('li').toggle();
        $container.find('li.loading').css({width:beforeWidth+'px',padding:(beforeHeight-$('.loading div').height())/2+'px 0'});

        if (j2w.SSB.Args.get('categoryid')) {
            redirURL += j2w.SSB.Args.get('categoryid') + '/';
        }

        if (options.socialSrc) {
            redirURL += '?reviewtoken=socialSubscribe&tcsetuptype=social&socialsrc=' + options.socialSrc + '&email=' + j2w.SSB.$activeButton.find('.emailGetter input[type=text]').val();
        } else {
            redirURL += '?email=' + j2w.SSB.$activeButton.find('.emailGetter input[type=text]').val();
        }

        if (j2w.SSB.Args.get('jobid')) {
            redirURL += '&jobid=' + j2w.SSB.Args.get('jobid');
        }

        if (j2w.SSB.Args.get('keywords').length) {
            redirURL += '&keywords=' + j2w.SSB.Args.get('keywords');
            redirURL += '&q=' + j2w.SSB.Args.get('keywords');
        }

        if (j2w.SSB.Args.get('locationsearch')) {
            redirURL += '&location=' + j2w.SSB.Args.get('locationsearch');
        } else if (j2w.SSB.Args.get('location')) {
            redirURL += '&location=' + j2w.SSB.Args.get('location');
        }

        // Pass along the locale from this subscribe source.
        redirURL += '&locale=' + j2w.SSB.Args.get('locale');

        // Set the URL to return to when the subscribe is complete.
        j2w.Navigation.setReturnURL(window.location.href, function () {
            document.location.href = redirURL;
        });
    }

